<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="项目" prop="projectName">
                <el-input
                        v-model="queryParams.projectName"
                        placeholder="请输入项目名称"
                        clearable
                        @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="网关编号" prop="gatewayNumber">
                <el-input
                        v-model="queryParams.gatewayNumber"
                        placeholder="请输入网关编号"
                        clearable
                        @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item label="卡号" prop="flowCardNumber">
                <el-input
                        v-model="queryParams.flowCardNumber"
                        placeholder="请输入流量卡卡号"
                        clearable
                        @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <!--      <el-form-item label="流量总额" prop="flowTotal">-->
            <!--        <el-input-->
            <!--          v-model="queryParams.flowTotal"-->
            <!--          placeholder="请输入流量总额"-->
            <!--          clearable-->
            <!--          size="small"-->
            <!--          @keyup.enter.native="handleQuery"-->
            <!--        />-->
            <!--      </el-form-item>-->
            <!--      <el-form-item label="剩余流量" prop="flowBalance">-->
            <!--        <el-input-->
            <!--          v-model="queryParams.flowBalance"-->
            <!--          placeholder="请输入剩余流量"-->
            <!--          clearable-->
            <!--          size="small"-->
            <!--          @keyup.enter.native="handleQuery"-->
            <!--        />-->
            <!--      </el-form-item>-->
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                        v-hasPermi="['business:gatewayInfo:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="el-icon-edit"
                        size="mini"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['business:gatewayInfo:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="el-icon-delete"
                        size="mini"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['business:gatewayInfo:remove']"
                >删除
                </el-button>
            </el-col>

            <!--      <el-col :span="1.5">-->
            <!--        <el-button-->
            <!--          plain-->
            <!--          size="mini"-->
            <!--          :disabled="single"-->
            <!--          @click="handleFlowCard"-->
            <!--          v-hasPermi="['business:gatewayInfo:edit']"-->
            <!--        >流量卡信息-->
            <!--        </el-button>-->
            <!--      </el-col>-->

            <!--      <el-col :span="1.5">-->
            <!--        <el-button-->
            <!--          type="warning"-->
            <!--          plain-->
            <!--          icon="el-icon-download"-->
            <!--          size="mini"-->
            <!--          @click="handleExport"-->
            <!--          v-hasPermi="['system:info:export']"-->
            <!--        >导出</el-button>-->
            <!--      </el-col>-->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!--  :cell-style="bgColor"   -->
        <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">

            <el-table-column type="expand">
                <template slot-scope="props">

                    <el-descriptions class="margin-top" :column="2" border>
                        <el-descriptions-item>
                            <template slot="label">
                                流量卡卡号
                            </template>
                            {{ props.row.flowCardNumber }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template slot="label">
                                流量卡有效期
                            </template>
                            {{ parseTime(props.row.effectiveTime, '{y}-{m}-{d}') }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template slot="label">
                                流量总额
                            </template>
                            {{ props.row.flowTotal }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template slot="label">
                                剩余流量
                            </template>
                            {{ props.row.flowBalance }}
                        </el-descriptions-item>

                    </el-descriptions>

                </template>
            </el-table-column>

            <el-table-column type="selection" width="55" align="center"/>

            <!--      <el-table-column label="主键" align="center" prop="gatewayInfoId" width="50" />-->
            <!--            <el-table-column label="序号" align="center" type="index" :index="calculateIndex"/>-->

            <el-table-column label="网关编号" align="center" prop="gatewayNumber" width="180"/>

            <el-table-column label="项目" align="center" prop="projectName"/>

            <el-table-column label="流量卡" align="center" prop="flowCardNumber">
                <template slot-scope="scope">
                    <el-link @click="handleFlowCard(scope.row)" type="primary" v-if="scope.row.flowCardNumber !== null"
                             :underline="false">已绑定
                    </el-link>
                    <el-link @click="handleFlowCard(scope.row)" type="info" v-if="scope.row.flowCardNumber === null"
                             :underline="false">未绑定
                    </el-link>
                </template>
            </el-table-column>

            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <el-link v-if="scope.row.status" type="primary" :underline="false">启用</el-link>
                    <el-link v-else type="info" :underline="false">禁用</el-link>
                </template>
            </el-table-column>

            <el-table-column label="添加人" align="center" prop="createBy"/>

            <el-table-column label="添加日期" align="center" prop="createTime">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>


            <!--   网关启用日期，换一个字段存储这个值，换到   -->
            <!--      <el-table-column label="项目启用日期" align="center" prop="beginPayTime" width="100">-->
            <!--        <template slot-scope="scope">-->
            <!--          <span>{{ parseTime(scope.row.beginPayTime, '{y}-{m}-{d}') }}</span>-->
            <!--        </template>-->
            <!--      </el-table-column>-->

            <!--   网关有效期，删除   -->
            <!--      <el-table-column label="项目有效期" align="center" prop="endPayTime" width="100">-->
            <!--        <template slot-scope="scope">-->
            <!--          <span>{{ parseTime(scope.row.endPayTime, '{y}-{m}-{d}') }}</span>-->
            <!--        </template>-->
            <!--      </el-table-column>-->

            <!-- 删除 -->
            <!--      <el-table-column label="上次缴费日期" align="center" prop="lastPayTime" width="100">-->
            <!--        <template slot-scope="scope">-->
            <!--          <span>{{ parseTime(scope.row.lastPayTime, '{y}-{m}-{d}') }}</span>-->
            <!--        </template>-->
            <!--      </el-table-column>-->


            <!--      <el-table-column label="天数" align="center">-->
            <!--        <template slot-scope="scope">-->
            <!--          <span v-if="scope.row.flowCardId !== null">{{ compareDate(scope.row.effectiveTime) }}</span>-->
            <!--        </template>-->
            <!--      </el-table-column>-->

            <!--      <el-table-column label="备注" align="center" prop="remark" />-->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">

                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['business:info:edit']"
                    >修改
                    </el-button>

                    <!--                    <el-button-->
                    <!--                            size="mini"-->
                    <!--                            type="text"-->
                    <!--                            icon="el-icon-bank-card"-->
                    <!--                            @click="handleFlowCard(scope.row)"-->
                    <!--                            v-hasPermi="['business:gatewayInfo:edit']"-->
                    <!--                    >流量卡-->
                    <!--                    </el-button>-->

                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['business:info:remove']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改网关基本信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="60px" size="small">

                <el-form-item label="编号" prop="gatewayNumber">
                    <el-input v-model="form.gatewayNumber" placeholder="请输入网关编号"/>
                </el-form-item>

                <el-form-item label="型号" prop="gatewayModel">
                    <el-select v-model="form.gatewayModel"
                               placeholder="请选择网关型号">
                        <el-option
                                v-for="item in gatewayModelList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"/>
                    </el-select>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status" size="small">
                        <el-radio-button :label="true">启用</el-radio-button>
                        <el-radio-button :label="false">禁用</el-radio-button>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                </el-form-item>

            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="submitForm">{{ buttonText }}</el-button>
                <el-button size="small" @click="cancel">取 消</el-button>
            </div>

        </el-dialog>


        <!-- 流量卡 -->
        <el-dialog title="流量卡" :visible.sync="flowCardOpen" width="500px" append-to-body>
            <FlowCard :row="flowCardForm" :key="flowCardFormKey"/>
        </el-dialog>

    </div>
</template>

<script>
import {
    listGatewayInfo,
    getGatewayInfo,
    delGatewayInfo,
    addGatewayInfo,
    updateGatewayInfo
} from '@/api/business/gatewayInfo'
import {listGatewayModelChoose} from '@/api/business/gatewayModel'

import FlowCard from './flowCard'

export default {
    name: 'Info',
    components: {
        FlowCard
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 网关基本信息表格数据
            infoList: [],
            // 弹出层标题
            title: '',
            buttonText: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                gatewayNumber: null,
                effectiveTime: null,
                lastPayTime: null,
                beginPayTime: null,
                endPayTime: null,
                flowCardNumber: null,
                flowTotal: null,
                flowBalance: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                gatewayNumber: [
                    {required: true, trigger: 'blur', message: '请输入网关编号'}
                ],
                gatewayModel: [
                    {required: true, trigger: 'blur', message: '请选择网关型号'}
                ]
            },

            flowCardOpen: false,
            flowCardForm: {},
            flowCardFormKey: 0,

            gatewayModelList: []
        }
    },
    created() {
        this.getList()
        this.getGatewayModelList()
    },
    // mounted() { //添加监听滚动条事件
    //   window.addEventListener('scroll', this.handleScroll, true)
    // },
    // destroyed() { //移除（跳转页面后移除）
    //   window.removeEventListener('scroll', this.handleScroll, true)
    // },
    methods: {

        bgColor({row, column, rowIndex, columnIndex}) {
            if (this.compareDate(row.effectiveTime) === '1' && columnIndex === 10) {
                return {
                    color: '#CCC'
                }
            }

            if (this.compareDate(row.effectiveTime) === '2' && columnIndex === 10) {
                return {
                    color: '#FF0000'
                }
            }
        },
        // 比较日期大小
        compareDate(effectiveTime) {

            let endDate = new Date(Date.parse(effectiveTime.replace(/-/g, '/')))

            let date = new Date()
            let year = date.getFullYear()
            let month = date.getMonth() + 1
            let day = date.getDate()
            let current = year + '-' + month + '-' + day

            console.log('流量卡过期时间，', endDate)

            let currentDate = new Date(Date.parse(current.replace(/-/g, '/')))
            if (currentDate > endDate) {
                //console.log("有效期：" + endTime, "当前日期：" + current)
                //console.log("过期了")
                return '1'
            }

            // 当前时间加上30天
            let ready = this.calculateDate(currentDate, 30)

            //console.log("加之后：" + ready)
            let readyDate = new Date(Date.parse(ready.replace(/-/g, '/')))

            console.log('加了30天之后：', readyDate)

            // 加了30天后再比较
            if (readyDate > endDate) {
                console.log(readyDate)
                return '2'
            }

        },

        calculateDate(date, days) {
            if (days === undefined || days === '') {
                days = 1
            }
            let newDate = new Date(date)
            // console.log("加之前：" + date)
            newDate.setDate(newDate.getDate() + days)
            let month = newDate.getMonth() + 1
            let day = newDate.getDate()
            return newDate.getFullYear() + '-' + month + '-' + day
        },

        calculateIndex(index) {
            const pageNum = this.queryParams.pageNum
            const pageSize = this.queryParams.pageSize
            return index + 1 + (pageNum - 1) * pageSize
        },
        /** 查询网关基本信息列表 */
        getList() {
            this.loading = true
            listGatewayInfo(this.queryParams).then(response => {
                this.infoList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            // 流量卡弹出框关闭
            this.flowCardOpen = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                gatewayInfoId: null,
                gatewayNumber: null,
                effectiveTime: null,
                lastPayTime: null,
                beginPayTime: null,
                endPayTime: null,
                flowCardType: null,
                flowCardNumber: null,
                flowTotal: null,
                flowBalance: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null
            }
            this.resetForm('form')
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.gatewayInfoId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加网关基本信息'
            this.buttonText = '添 加'
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const gatewayInfoId = row.gatewayInfoId || this.ids
            getGatewayInfo(gatewayInfoId).then(response => {
                this.form = response.data
                this.open = true
                this.title = '修改网关基本信息'
                this.buttonText = '修 改'
            })
        },

        /** 流量卡信息 */
        handleFlowCard(row) {
            this.flowCardForm = row
            this.flowCardFormKey += 1
            this.flowCardOpen = true
        },

        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.gatewayInfoId != null) {
                        updateGatewayInfo(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addGatewayInfo(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const gatewayInfoIds = row.gatewayInfoId || this.ids
            this.$modal.confirm('是否确认删除网关基本信息编号为"' + gatewayInfoIds + '"的数据项？').then(function () {
                return delGatewayInfo(gatewayInfoIds)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/info/export', {
                ...this.queryParams
            }, `info_${new Date().getTime()}.xlsx`)
        },

        getGatewayModelList() {

            this.gatewayModelList = []

            listGatewayModelChoose().then(response => {

                for (let item of response.data) {
                    let temp = {}
                    temp['value'] = item.gatewayModelId
                    temp['label'] = item.gatewayModelName

                    this.gatewayModelList.push(temp)
                }
            }, error => {
            })
        }
    }
}
</script>
